<?php

namespace app\common\model;

use think\Db;
use think\Model;

class Admin extends Model
{
    //删除用户
    public function deleteAdmin($userInfo){

        $result = $this->where('id',$userInfo['id'])->delete();
        if (!$result){
            return '删除用户信息失败';
        }
        $result = Db::table('login')->where('username',$userInfo['username'])->delete();
        if (!$result){
            return '删除登陆信息失败';
        }
        $result =Db::table('powers')->where('admin_id',$userInfo['id'])->delete();
        if ($result){
            return 1;
        }else{
            return '删除失败权限失败';
        }
    }
    //添加用户
    public function addAdmin($data,$power){
        $validate = new  \app\common\validate\Admin();
        if (!$validate->scene('add')->check($data)){
            return $validate->getError();
        }

        $adminId = $this->allowField(true)->insertGetId($data);
        if($adminId){
            foreach ($power as $v){
                $power2[]= [
                    'admin_id'=> $adminId,
                    'function' => $v
                ];
            }
            $data2 = [
                'username' => $data['username'],
                'nickname' => $data['nickname'],
                'password' => md5($data['username'])
            ];
            $loginId =Db::table('login')->insertGetId($data2);

            if ($loginId){

                $result = Db::table('powers')->insertAll($power2);
                if ($result){
                    return 1;
                }else{
                    $result = $this->where('id',$adminId)->delete();
                    Db::table('login')->where('id',$loginId)->delete();
                    return '权限写入错误，注册失败';
                }

            }else{
                $result = $this->where('id',$adminId)->delete();
                return '登陆表单无法写入,注册失败';
            }

           }else{
              return '用户信息写入错误，注册失败';
        }



    }
    //修改用户信息
    public function updateAdmin($id ,$data){
        $result = $this->where('id',$id)->update($data);
        $data2 = [
            'username' => $data['username'],
            'nickname' => $data['nickname'],
        ];
        if ($result){
            $result2 = Db::table('login')->where('username',$data['username'])->update($data2);
            if ($result2){
                return 1;
            }else{
                return '登陆表单更新失败';
            }

        }else{
            return '更新失败';
        }

    }


}
